<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 开发环境版本，包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <!-- 因为 AJAX 库和通用工具的生态已经相当丰富，Vue 核心代码没有重复 -->
    <!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 -->

    <script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>
</head>

<body>

    <div id="app">
        你的问题：<input v-model="question" />
        <div> {{answer}}</div>
    </div>
</body>


<script>
    var app = new Vue({
        el: "#app",
        data: {
            question: '',
            answer: '我无法回答问题，除非你问了我问题',

        },
        //监听操作  是否有提问
        watch: {
            question: function () {
                this.answer = "输入问题中……"
                this.debouncedGetAnswer();
                console.log("debouncedGetAnswer被调用了")
            }
        },
        //    500 毫秒回答  -回答时间
        created: function () {
            this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)
        },


        methods: {
            getAnswer: function () {
                if (this.question.indexOf('?') === -1) {
                    this.answer = '通常提问题里面都会有 问号 ? '
                    return
                }
                this.answer = '对了...'
                var vm = this
                axios.get('https://yesno.wtf/api')
                    .then(function (response) {
                        vm.answer = _.capitalize(response.data.answer)
                    })
                    .catch(function (error) {
                        vm.answer = 'Error! Could not reach the API. ' + error
                    })
            }
        }
    })

</script>

</html>